package com.example.jpa.demo_jpa.service.impl;

import com.example.jpa.demo_jpa.dao.AyuserDao;
import com.example.jpa.demo_jpa.model.AyUser;
import com.example.jpa.demo_jpa.model.PhoneType;
import com.example.jpa.demo_jpa.repository.AyUserRepository;
import com.example.jpa.demo_jpa.service.AyUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Transactional
@Service
public class AyUserServiceImpl implements AyUserService {
    @Resource
    private AyUserRepository ayUserRepository;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    private AyuserDao ayuserDao;

    private static final String ALL_USER = "ALL_USER_LIST";
    @Override
    public AyUser findbyId(String id) {
        //step.1 查询Redis缓存中的所有数据
        List<AyUser> ayUserList = redisTemplate.opsForList().range(ALL_USER,0,-1);
        if (ayUserList != null&&ayUserList.size() >0){
            for (AyUser ayUser:ayUserList
                    ) {
                if (ayUser.getId().equals(id)){
                    return ayUser;
                }
            }
        }
        //step.2 查询数据库中的数据
        AyUser ayUser = ayUserRepository.findById(id).get();
        if (ayUser != null){
            //step.3 将数据插入到Redis缓存中
            redisTemplate.opsForList().leftPush(ALL_USER,ayUser);
        }
        return ayUser;
    }
    @Override
    public List<AyUser> findAll() {
        return ayUserRepository.findAll();
    }
    @Override
    public AyUser save(AyUser ayUser) {
        return ayUserRepository.save(ayUser);
    }
    @Override
    public void delete(String id) {
        ayUserRepository.deleteById(id);
    }

    @Override
    public List<AyUser> findByName(String name) {
        return ayUserRepository.findByName(name);
    }

    @Override
    public AyUser findbyName(String name) {
        return ayuserDao.findByNameM(name);
    }
}
